/**
 * TagSpaces - universal file and folder organizer
 * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License (version 3) as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

import React, { ChangeEvent, useRef, useReducer, useEffect } from 'react';
import { Theme } from '@mui/material/styles';
import withStyles from '@mui/styles/withStyles';
import createStyles from '@mui/styles/createStyles';
import Button from '@mui/material/Button';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import Dialog from '@mui/material/Dialog';
import i18n from '-/services/i18n';
import DialogCloseButton from '-/components/dialogs/DialogCloseButton';
import useTheme from '@mui/styles/useTheme';
import useMediaQuery from '@mui/material/useMediaQuery';
import { QRCode } from 'react-qrcode-logo';
import InfoIcon from '-/components/InfoIcon';
import InputAdornment from '@mui/material/InputAdornment';
import TextField from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import PlatformIO from '-/services/platform-facade';
import AppConfig from '-/AppConfig';
import useFirstRender from '-/utils/useFirstRender';

interface Props {
  open: boolean;
  onClose: () => void;
  path: string;
  showNotification: (message: string) => void;
  locationId: string;
  switchLocationType: (locationId: string) => Promise<string | null>;
  switchCurrentLocationType: (currentLocationId: string) => Promise<boolean>;
}

const QRTextField = withStyles((theme: Theme) =>
  createStyles({
    root: {
      marginTop: 12,
      '& .MuiInputBase-root': {
        height: 450
      }
    }
  })
)(TextField);

function LinkGeneratorDialog(props: Props) {
  const { open, onClose, path, showNotification } = props;
  const linkValidityDuration = useRef<number>(60 * 15);
  const signedLink = useRef<string>(undefined);
  const [ignored, forceUpdate] = useReducer(x => x + 1, 0);
  const theme = useTheme();
  const fullScreen = useMediaQuery(theme.breakpoints.down('md'));

  useEffect(() => {
    setSignedLink();
  }, []);

  function setSignedLink() {
    props.switchLocationType(props.locationId).then(currentLocationId => {
      signedLink.current = PlatformIO.getURLforPath(
        path,
        linkValidityDuration.current
      );
      forceUpdate();
      props.switchCurrentLocationType(currentLocationId);
    });
  }

  return (
    <Dialog
      open={open}
      onClose={onClose}
      fullScreen={fullScreen}
      keepMounted
      scroll="paper"
    >
      <DialogTitle>
        {i18n.t('core:generateDownloadLink')}{' '}
        <DialogCloseButton onClose={onClose} />
      </DialogTitle>
      <DialogContent
        style={{ overflow: AppConfig.isFirefox ? 'auto' : 'overlay' }}
      >
        <TextField
          style={{ marginTop: 8 }}
          select
          fullWidth={true}
          label={
            <>
              {i18n.t('core:linkValidity')}
              <InfoIcon tooltip={i18n.t('core:linkValidityTooltip')} />
            </>
          }
          value={linkValidityDuration.current}
          onChange={(event: ChangeEvent<HTMLInputElement>) => {
            linkValidityDuration.current = parseInt(event.target.value, 10);
            setSignedLink();
          }}
        >
          <MenuItem value={60 * 15}>15 {i18n.t('core:minutes')}</MenuItem>
          <MenuItem value={60 * 60}>60 {i18n.t('core:minutes')}</MenuItem>
          <MenuItem value={60 * 60 * 24}>1 {i18n.t('core:day')}</MenuItem>
          <MenuItem value={60 * 60 * 24 * 3}>3 {i18n.t('core:days')}</MenuItem>
          <MenuItem value={60 * 60 * 24 * 7}>7 {i18n.t('core:days')}</MenuItem>
        </TextField>
        <TextField
          margin="dense"
          name="path"
          style={{ marginTop: 15 }}
          InputProps={{
            readOnly: true,
            endAdornment: (
              <InputAdornment position="start">
                <Button
                  data-tid="copySharingLinkTID"
                  onClick={() => {
                    navigator.clipboard
                      .writeText(signedLink.current)
                      .then(() => {
                        showNotification(i18n.t('core:linkCopied'));
                      });
                  }}
                  color="primary"
                >
                  {i18n.t('core:copy')}
                </Button>
              </InputAdornment>
            )
          }}
          label={
            <>
              {i18n.t('core:downloadLink')}
              {/* <InfoIcon
                tooltip={i18n.t(
                  'Link for time limited sharing on the Internet'
                )}
              /> */}
            </>
          }
          fullWidth={true}
          value={signedLink.current}
        />
        <QRTextField
          margin="dense"
          name="path"
          label={i18n.t('core:qrCode')}
          value={' '}
          InputProps={{
            readOnly: true,
            startAdornment: (
              <InputAdornment position="start">
                <QRCode
                  id="qr-code-link"
                  value={signedLink.current}
                  size={350}
                  enableCORS={true}
                  // logoWidth={64}
                  // logoHeight={64}
                  // logoImage=""
                />
              </InputAdornment>
            )
          }}
        />
      </DialogContent>
      <DialogActions>
        <Button data-tid="closeLinkTID" onClick={onClose} color="primary">
          {i18n.t('core:close')}
        </Button>
      </DialogActions>
    </Dialog>
  );
}

export default LinkGeneratorDialog;
